<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>vue双向绑定原理实现</title>
</head>
<body>
<div id='app'>
	<input v-model="message" /><br>
	<input v-model="message" /><br>
	<div v-bind='message'></div>
	<div v-bind='message'></div>
</div>
<script>
const modelData = {
	message: '',
}
const modelElem = document.querySelectorAll('[v-model="message"]');

// 绑定事件
for(let i = 0; i < modelElem.length; i++) {
	modelElem[i].onkeyup = function() {
		modelData[this.getAttribute("v-model")] = this.value;// 更改对象的数据
	}
}
// 劫持 get 和 set
Object.defineProperty(modelData, 'message', {
	get: function() {
		return this.value;
	},
	set: function(val) {
		console.log(val);
		// 更改模板的值-输入框
		const elemModels = document.querySelectorAll('[v-model="message"]');
		for(let i = 0; i < elemModels.length; i++) {
			elemModels[i].value = val;
		}
		// 更改模板的值-值
		const elemBinds = document.querySelectorAll('[v-bind="message"]');
		for(let i = 0; i < elemBinds.length; i++) {
			elemBinds[i].innerHTML = val;
		}
		// 设定新值
		this.value = val;
	}
})
</script>
</body>
</html>